<template>
  <div class="recycle-clue">
    <div class="current-students-search">
      <el-form :model="form" ref="ruleFormRef" label-width="auto">
        <el-row :gutter="0" style="margin-bottom: 10px">
          <el-col :span="6">
            <el-form-item label="搜索学员:">
              <el-input
                v-model="searchName"
                style="width: 80%"
                placeholder="请输入学员姓名/手机号"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学员来源:">
              <el-select
                v-model="searchJoinWay"
                placeholder="请选择学员来源"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in joinWayList.value"
                  :key="item.dictCode"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学员创建人:">
              <el-select
                v-model="creatorName"
                placeholder="请选择学员创建人"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in followPeopleList"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id"
                >
                  {{ item.nickName }}{{ !item.isJob ? '(已离职)' : '' }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="Search" @click="toSearch"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="toClear(ruleFormRef)"
              >重置</el-button
            >
          </el-col>
        </el-row>
        <el-row :gutter="0" style="margin-bottom: 10px">
          <el-col :span="6" style="padding-right: 4%">
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="cTime"
                type="daterange"
                unlink-panels
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 80%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="删除人:">
              <el-select
                v-model="deletePeople"
                placeholder="请选择删除人"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in followPeopleList"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="padding-right: 4%">
            <el-form-item label="删除日期:">
              <el-date-picker
                v-model="dTime"
                type="daterange"
                unlink-panels
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 80%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="0" style="margin-bottom: 10px">
            <el-col :span="8">
              <span class="search-label"> 删除原因:</span>
              <el-select
                v-model="studyPeople"
                placeholder="请选择学管师"
                style="width: 80%"
                @change="toSearch"
                clearable
              >
                <el-option
                  v-for="item in peopleList.value"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
          </el-row> -->
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="students-table">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="学员姓名" fixed="left" width="180">
          <template #default="scope">
            <router-link
              :to="'/registrar/studentsDetails/detail/' + scope.row.id"
              class="link-type"
            >
              <div style="display: flex; align-items: center">
                <span
                  style="margin-right: 10px; color: #67c23a; cursor: pointer"
                  >{{ scope.row.name }}</span
                >
                <el-icon v-if="scope.row.gender == '1'" style="color: #fb6465"
                  ><Female
                /></el-icon>
                <el-icon
                  v-else-if="scope.row.gender == '0'"
                  style="color: #4791ed"
                  ><Male
                /></el-icon>
              </div>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column
          property="mobile"
          label="手机号"
          fixed="left"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <el-table-column
          property="joinName"
          label="学员来源"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <el-table-column
          property="creatName"
          label="学员创建人"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <el-table-column
          property="addTime"
          label="创建时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <el-table-column
          property="deletePeople"
          label="删除人"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <el-table-column
          property="counselor"
          label="最后跟进人"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <el-table-column
          property="deleteTime"
          label="删除时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        />
        <!-- <el-table-column
          property="deleteReason"
          label="删除原因"
          show-overflow-tooltip
          :formatter="formatName"
        /> -->
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="toRestore(scope.row)"
              v-hasPermi="['sales:clue:recycle']"
            >
              还原
            </el-button>
            <!-- <el-button link type="primary" @click="toDelete(scope.row)">
              彻底删除
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @pagination="toGetCurrentStudentsList"
      />
      <div style="height: 10px"></div>
    </div>
    <ShareDialog
      :isShowShare="isShowShare"
      :shareType="shareType"
      :students="multipleSelection"
      @update:isShowShare="updateShowShare"
      @update:tableList="toGetCurrentStudentsList"
    />
  </div>
</template>

<script setup>
import Pagination from '@/components/Pagination/index.vue'
import ShareDialog from '../../../registrar/student/components/shareDialog/index.vue'
import { ref, reactive, provide } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import useRegistrarStore from '@/store/modules/registrar'
import {
  getStudentsList,
  getStaffList,
  getJoinWayList,
  getClassList,
  getGradeList,
  deleteClue,
  getFollowPeopleList,
} from '@/api/studentManagement/index.js'
const { proxy } = getCurrentInstance()
const loading = ref(true)
//创建store
const registrarStore = useRegistrarStore()
//筛选
const searchName = ref('') //学员搜索
const cTime = ref('')
const dTime = ref('')
//获取学员来源下拉列表
const searchJoinWay = ref('') //学员来源
const joinWayList = reactive([]) //学员来源列表
provide('joinWayList', joinWayList) //传值给后代
const toGetJoinWayList = async () => {
  try {
    const res = await getJoinWayList()
    if (res.code == 200) {
      joinWayList.value = res.data
      registrarStore.setJoinWayList(joinWayList.value)
    }
  } catch (error) {
    console.error('获取学员来源下拉列表失败:', error)
  }
}
onMounted(toGetJoinWayList)

//跟进人&学员创建人
const deletePeople = ref('') //删除人
const creatorName = ref('') //学员创建人
const followPeopleList = ref([])
const toFollowPeopleList = async () => {
  try {
    const res = await getFollowPeopleList({ pageNum: 1, pageSize: 9999 })
    if (res.code == 200) {
      followPeopleList.value = res.rows
    }
  } catch (error) {
    console.error('获取学员创建人下拉列表失败:', error)
  }
}
onMounted(toFollowPeopleList)

//获取所在班级下拉列表
const classN = ref('')
const classList = reactive([]) //所在班级列表
const toGetClassList = async () => {
  try {
    const res = await getClassList({})
    if (res.code == 200) {
      classList.value = res.data
      registrarStore.setClassList(classList.value)
    }
  } catch (error) {
    console.error('获取所在班级下拉列表失败:', error)
  }
}
onMounted(toGetClassList)
//获取年级下拉列表
const gradeName = ref('')
const gradeList = reactive([]) //所在班级列表
const toGetGradeList = async () => {
  try {
    const res = await getGradeList({})
    if (res.code == 200) {
      gradeList.value = res.data
      registrarStore.setGradeList(gradeList.value)
    }
  } catch (error) {
    console.error('获取年级下拉列表失败:', error)
  }
}
onMounted(toGetGradeList)

//筛选学员列表
function toSearch() {
  console.log('ctime', cTime.value)

  toGetCurrentStudentsList()
}

//控制折叠
const isCollapse = ref(true)
function setCollapse() {
  isCollapse.value = !isCollapse.value
}
//控制分配弹窗
const isShowShare = ref(false)
const shareType = ref(1)
const openShareDialog = (type) => {
  if (multipleSelection.value.length) {
    shareType.value = type
    isShowShare.value = true
  } else {
    ElMessage({
      message: '请选择要分配的学员',
      type: 'warning',
    })
  }
}
const updateShowShare = (value) => {
  isShowShare.value = value
}

//表格多选操作
const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  console.log('444', multipleSelection.value)
}
//分页器
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
//处理日期格式
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以加1
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
//获取表格数据
const tableData = ref([])
const toGetCurrentStudentsList = async () => {
  loading.value = true
  const params = {
    type: 5,
    mine: 0,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    wxParam: searchName.value,
    joinWay: searchJoinWay.value,
    deletePeopleId: deletePeople.value,
    creator: creatorName.value,
    startTime: cTime.value ? formatDate(cTime.value[0]) : '',
    endTime: cTime.value ? formatDate(cTime.value[1]) : '',
    delStartTime: dTime.value ? formatDate(dTime.value[0]) : '',
    delEndTime: dTime.value ? formatDate(dTime.value[1]) : '',
  }
  // console.log('params', params.startTime)

  try {
    const res = await getStudentsList(params)
    if (res.code == 200) {
      total.value = res.total
      tableData.value = res.rows
      loading.value = false
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
  }
}
onMounted(toGetCurrentStudentsList)
//表格没有数据显示'-'
const formatName = (row, column, cellValue) => {
  return cellValue === '' || cellValue === null ? '-' : cellValue
}

//还原学员
const toRestore = (row) => {
  ElMessageBox.confirm('是否还原学员', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // const params = {
      //   type: 3,
      //   [row.stage === 3 ? 'recordId' : 'id']: row.id,
      // }
      const params = {
        id: row.id,
        type: 3,
        ...(row.recordId && { recordId: row.recordId }),
      }
      try {
        const res = await deleteClue(params)
        if (res.code == 200) {
          toGetCurrentStudentsList()
          ElMessage({
            type: 'success',
            message: '还原成功',
          })
        } else {
          ElMessage({
            type: 'error',
            message: '还原失败',
          })
        }
      } catch (error) {
        console.error('还原失败:', error)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消还原学员',
      })
    })
}
//删除学员
const toDelete = (row) => {
  ElMessageBox.confirm('是否彻底删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await deleteClue({
          id: row.id,
          type: 2,
        })
        if (res.code == 200) {
          toGetCurrentStudentsList()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        } else {
          ElMessage({
            type: 'error',
            message: '删除失败',
          })
        }
      } catch (error) {
        console.error('删除失败:', error)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}
//清空搜索内容
const toClear = () => {
  searchName.value = ''
  searchJoinWay.value = ''
  deletePeople.value = ''
  creatorName.value = ''
  cTime.value = ''
  dTime.value = ''
  pageNum.value = 1
  toGetCurrentStudentsList()
}
</script>

<style lang="scss" scoped>
.recycle-clue {
  // position: relative;
  .current-students-search {
    position: relative;
    margin-bottom: 30px;
    .use-btn {
      position: absolute;
      top: 0;
      right: 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-left: 40px;
      width: 10%;
      height: 30px;
      cursor: pointer;
      .collapse-btn {
      }
    }
    .search-label {
      display: inline-block;
      width: 18%;
      text-align: right;
      margin-right: 8px;
      font-size: 14px;
    }
    .current-students-search-main {
      width: 90%;

      .search-collapse {
        // height: 500px;
        // background-color: red;
      }
    }
  }
  .manage-students {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    height: 40px;
    // background-color: red;
  }
}
</style>